<template>
  <el-dialog v-model="dialogVisible" title="系统激活" width="718px" draggable>
    <el-form ref="ruleFormRef" :model="ruleForm" label-suffix=":" :rules="rules" label-width="100px">
      <div class="text-align-center mb15">
        <el-text class="fsize26" type="danger">提示：输入激活码进行系统激活，要激活吗？</el-text>
      </div>
      <!-- slice(0, 11) -->
      <el-form-item label="有效期至" prop="">
        {{ activation.endate }}
        <span style="color: #f78888" class="fsize20">
          {{ !isPast ? "（系统已过期，为保障正常使用请尽快激活）" : "" }}
        </span>
      </el-form-item>
      <el-form-item label="激活码" prop="facCode">
        <el-input v-model="ruleForm.facCode" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">开始激活</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { doActivation } from "@/api/modules/system";
import { useUserStore } from "@/stores/modules/user";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { computed, reactive, ref } from "vue";

const dialogVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
const userStore = useUserStore();
const activation = computed(() => userStore.activation);
const ruleForm = reactive({
  facCode: ""
});
const openDialog = () => {
  // isOutDate().then(res => {
  //   ruleForm.endate = res.data.endate;
  // });
  dialogVisible.value = true;
};
const rules = reactive<FormRules>({
  facCode: [{ required: true, message: "请输入激活码", trigger: "blur" }]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  // if (new Date() < new Date(activation.value.endate)) return ElMessage.error("有效期已过期");
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      doActivation(ruleForm).then(res => {
        userStore.setActivation(res.data);
        ElMessage({
          message: "系统激活成功!",
          grouping: true,
          type: "success"
        });
        dialogVisible.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const isPast = computed(() => new Date() < new Date(activation.value.endate));

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};

defineExpose({ openDialog });
</script>
